<template>
  <div>
    <!-- 气瓶流转 -->
    <el-table-form ref="form" :model="query">
      <el-form-item label="操作时间:" :table-form-merge="2">
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="发生机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="handleClear"
        />
      </el-form-item>
      <el-form-item label="操作人:" prop="ownerIdList">
        <el-select v-model="query.ownerIdList" clearable filterable multiple collapse-tags style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="(item,index) in ownersList"
            :key="index"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="气瓶编号:" prop="chipCode">
        <el-input v-model="query.chipCode" />
      </el-form-item>
      <el-form-item label="操作环节:" prop="operateType">
        <el-select v-model="query.operateType" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in operateTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异常气瓶:" prop="bottleReturnTag">
        <el-select v-model="query.bottleReturnTag" clearable style="width: 100%;" placeholder="请选择">
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="匹配订单:" prop="orderCode">
        <el-input v-model="query.orderCode" clearable />
      </el-form-item>
      <el-form-item label="无空瓶原因:" prop="bottleTag">
        <el-select v-model="query.bottleTag" clearable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in bottleTagMap"
            :key="item.value"
            :label="item.desc"
            :value="item.desc"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button v-permission="2" type="primary" @click="showRelease">初始化</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="3"
        type="primary"
        icon="el-icon-download"
        :loading="$loadingPlugin.batchExp"
        @click="batchExp"
      >导出</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <bottle-detail ref="bottleDetail" :type="1" />
    <detail ref="detail" type="get" />
    <recovery ref="recovery" @upDataTable="search" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
      :transactor-list="transactorList"
    />
    <realseBottle ref="realseBottle" :tree-data="treeData" @upDataTable="search" />
    <cylinderDetail ref="cylinderDetail" />
    <outboundDetail ref="outboundDetail" />
    <warehousingDetail ref="warehousingDetail" />
    <outStorageDetail ref="outStorageDetail" :stock-out-type-map="stockOutTypeMap" :gd-status-map="gdStatusMap" />
    <putStorageDetail ref="putStorageDetail" :stock-in-type-map="stockInTypeMap" :gd-status-map="gdStatusMap" />
    <popups ref="popups" :ent-type-list="entTypeList" :tree-data="treeData" :calc-type-list="calcTypeList" :payment-method-list="paymentMethodMap" :pay-status-list="payStatusMap" :paymen-fil-list="paymenFilList" :customer-type="customerTypeMap" />
    <plannedFillingOrderDetail ref="plannedFillingOrderDetail" :bill-status-map="fillBillStatusMap" />
    <returnOfTheAudit ref="returnOfTheAudit" :payment-method-map="paymentMethodMap" />
    <swapOrderDetails ref="swapOrderDetails" :bill-status-map="swapBillStatusMap" />
  </div>
</template>

<script>
  import { parseTime } from '@/utils'
  import { stockTransWin, bottleTrace, csDeliverUserList, queryMap, callorBottleExport, queryCsmTypeMap } from '@/api'
  import { mapGetters } from 'vuex'
  import bottleDetail from './bottleDetail.vue'
  import detail from './detail.vue'
  import recovery from './recovery.vue'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import orderDetail from '../../../orderCenter/orderManage/components/OrderDetails.vue'
  import realseBottle from './realseBottle.vue'
  import CylinderDetail from '@/views/components/cylinderDetail/index'
  import outboundDetail from './outboundDetail'
  import warehousingDetail from './warehousingDetail'
  import outStorageDetail from '../../outPutStorageManage/components/outStorageDetail.vue'
  import putStorageDetail from '../../outPutStorageManage/components/putStorageDetail.vue'
  import plannedFillingOrderDetail from '../../stockManage/plannedFillingOrder/components/Detail.vue'
  import ReturnOfTheAudit from '@/views/orderCenter/refundsManage/components/ReturnOfTheAudit.vue'
  import swapOrderDetails from '@/views/orderCenter/swapOrderManage/components/OrderDetails.vue'
  import Popups from '@/views/customerCenter/depositManage/components/Popups.vue'

  export default {
    name: 'cylinderCirculation',
    components: {
      bottleDetail, detail, recovery, orderDetail, realseBottle, CylinderDetail, outboundDetail, warehousingDetail,
      outStorageDetail, putStorageDetail, Popups, plannedFillingOrderDetail, ReturnOfTheAudit, swapOrderDetails
    },
    props: {
    },
    data() {
      return {
        dateType: 'operatorTime',
        txt: '',
        date: [new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)],
        updateList: [], // 批量操作
        ids: [],
        actionColWidth: 80,
        invalidStr: '',
        ownersList: [],
        searchParams: {},
        query: {
          orgSNNo: '',
          ownerIdList: [],
          chipCode: '',
          orderCode: '',
          operateType: '',
          bottleReturnTag: '',
          bottleTag: ''
        },
        billStatusMap: [
          {
            value: 1,
            desc: '出库中'
          },
          {
            value: 2,
            desc: '已提交'
          },
          {
            value: 3,
            desc: '已撤销'
          }
        ],
        tableData: {
          total: 0,
          data: []
        },
        paymentMethodMap: [],
        payStatusMap: [],
        orderFlagMap: [],
        orderSourceMap: [],
        orderStatusMap: [],
        transactorList: [],
        operateTypeMap: [],
        bottleTagMap: [],
        stockOutTypeMap: [],
        stockInTypeMap: [],
        gdStatusMap: [],
        entTypeList: [],
        calcTypeList: [],
        paymenFilList: [],
        customerTypeMap: [],
        treeData: [],
        fillBillStatusMap: [],
        swapBillStatusMap: []
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'exportDomain', 'orgList'
      ]),
      csmStatusMap: function() {
        return this.csmStatus.filter(item => item.value !== -1)
      },
      column: function() {
        const cols = [
          {
            type: 'index'
          },
          {
            prop: 'chipCode',
            label: '气瓶芯片号',
            width: 110,
            render: (h, { row }) => (<el-link underline={false} onClick={() => this.showCylinderDetail(row.chipCode)}>{row.chipCode}</el-link>)
          },
          {
            prop: 'specName',
            label: '规格型号',
            width: 140
          },
          {
            prop: 'operateTypeName',
            label: '操作环节',
            width: 140
          },
          {
            prop: 'operateTime',
            label: '操作时间',
            width: 160,
            render: (h, { row }) => row.operateTime && <span>{ parseTime(row.operateTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'bottleTypeName',
            width: 80,
            label: '瓶型'
          },
          {
            prop: 'bottleTag',
            width: 160,
            label: '无空瓶原因'
          },
          {
            prop: 'orgName',
            width: 200,
            label: '发生机构'
          },
          {
            prop: 'ownerName',
            label: '操作人'
          },
          {
            prop: 'orderCode',
            label: '匹配订单',
            width: 110,
            render: (h, { row }) => (<el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link>)
          },
          {
            prop: 'billCode',
            label: '出入库单号',
            width: 160,
            // 退瓶消单不展示
            render: (h, { row }) => (row.operateType !== 12 && (<el-link underline={false} onClick={() => this.showDetail(row)}>{row.billCode}</el-link>))
          },
          {
            prop: 'auditor',
            width: 110,
            label: '审核人'
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'bottleReturnTag',
            width: 100,
            label: '异常气瓶',
            formatter: row => {
              return row.bottleReturnTag === 1
                ? '是' : ''
            }
          }
        ]
        return cols
      }
    },
    mounted() {
      this.queryOptionsMap()
      this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8, res9, res10, res11, res12, res13, res14, res15, res16] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'InvenChipOperateType' }),
          mergeAsyncFunc(queryMap, { enumName: 'InvenReturnType' }),
          mergeAsyncFunc(queryMap, { enumName: 'StockOutType' }),
          mergeAsyncFunc(queryMap, { enumName: 'StockInType' }),
          stockTransWin(),
          queryCsmTypeMap(),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'FillBillStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'BarterBillStatus' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
        this.operateTypeMap = res8.data // 操作环节
        this.bottleTagMap = res9.data.filter(item => item.value === 1 || item.value === 3) // 过滤不要的（兵）
        this.stockOutTypeMap = res10.data // 出库类型
        this.stockInTypeMap = res11.data // 入库类型
        this.gdStatusMap = JSON.parse(res12.data.gdStatusMap) // 商品状态枚举
        this.entTypeList = res13.data // 客户类型
        this.calcTypeList = res14.data.filter((item) => item.value !== 0) // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        this.paymentMethodMap.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.fillBillStatusMap = res15.data // 计划装瓶单状态
        this.swapBillStatusMap = res16.data // 换瓶单状态
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          json: { ...this._getQuery(this.query) },
          pageIndex: currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.json.operateTime = moment(this.date[0]).format()
          query.json.operateTimeEnd = moment(this.date[1]).format()
        }
        this.searchParams = {
          ...(query.json),
          pageIndex: query.currentPage,
          pageSize: query.pageSize
        }
        const res = await bottleTrace(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'ownerIdList', [])
        this.getOwnersList(value)
      },
      handleClear() {
        this.$set(this.query, 'ownerIdList', [])
        this.ownersList = []
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const res = await csDeliverUserList({
          deliveryOrgId: org.orgId,
          deliveryOrgSNNo: org.orgSNNo,
          containWebUserflag: 1
        })
        this.ownersList = res.data
      },
      // 出库瓶号详情弹窗
      async openBottleDetail(row) {
        await this.$refs.bottleDetail.open(row)
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      async recovery(row, type) {
        await this.$refs.recovery.open(row, type, 'get')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 气瓶详情
      async showCylinderDetail(val) {
        if (val) {
          await this.$refs.cylinderDetail.open(val)
        } else {
          this.$message.warning('暂无相关信息')
        }
      },
      async openOrderDetail(row) {
        if (row.operateType === 12) {
          this.$refs.popups.open({ ...row, depositCode: row.orderCode, depositId: '', depStatus: '' }, 'info')
        } else {
          await this.$refs.orderDetail.open(row)
        }
      },
      async showDetail(row) {
        if (row.operateType === 5) {
          await this.$refs.outboundDetail.open({ invenBillCode: row.billCode })
        }
        if (row.operateType === 7) {
          await this.$refs.warehousingDetail.open({ invenBillCode: row.billCode })
        }
        if (row.operateType === 3 || row.operateType === 9) {
          await this.$refs.outStorageDetail.open({ stockOutCode: row.billCode })
        }
        if (row.operateType === 1 || row.operateType === 4) {
          await this.$refs.putStorageDetail.open({ stockInCode: row.billCode })
        }
        if (row.operateType === 10 || row.operateType === 11) {
          await this.$refs.returnOfTheAudit.open({ billCode: row.billCode }, 'detail')
        }
        if (row.operateType === 14) {
          await this.$refs.plannedFillingOrderDetail.open({ fillCode: row.billCode })
        }
        // 用户验收环节需区分换货和领瓶单号，展开不同的详情页
        if (row.operateType === 6) {
          if (row.billCode.startsWith('HH')) {
            await this.$refs.swapOrderDetails.open({ billCode: row.billCode })
          } else if (row.billCode.startsWith('LP')) {
            await this.$refs.outboundDetail.open({ invenBillCode: row.billCode })
          }
        }
        this.search()
      },
      showRelease() {
        this.$refs.realseBottle.open()
      },
      // 导出
      batchExp() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          const paramInfo = _this._getQuery(params)
          callorBottleExport({
            paramInfo: paramInfo,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-form-item {
  margin-bottom: 10px;
}
.disabled {
  color: #909399 !important;
}
.footText {
  position: absolute;
  right: 10px;
  bottom: 5px;
  color: #F56C6C;
}
</style>
